import { Button, Form, Input } from 'antd';
import classes from './LoginInput.module.css';
import {useRouter} from "next/router";
import { v4 as uuidv4 } from 'uuid';
import {User, Userlist} from '../../store/modules/user'
import {useDispatch} from "react-redux";
import socket from "../../ws";

function LoginInput(){
    const router = useRouter();
    const dispatch = useDispatch();

    //登陆
    const onFinish = (values: any) => {
        fetch('https://api.multiavatar.com/'
            +JSON.stringify(values))
            .then(res => res.text())
            .then(svg =>  socket.emit('login',{
                username:values.username,
                avatar:svg,
                id:uuidv4()
            }))

        //登陆失败
        socket.on('loginError',(data) => {
            alert(data.msg)
        })

        //登陆成功
        socket.on('loginSuccess',(data) => {
            dispatch(User({username:data.username,avatar:data.avatar}))
            router.push('/chat')
            socket.on('userlist',(data) => {
                dispatch(Userlist(data.msg))
            })
        })
    };



    return(
        <div className={classes.form}>
            <br/>
            <br/>
            <br/>
            <Form
                name="basic"
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item
                    label="Username"
                    name="username"
                    rules={[{ required: true, message: 'Please input your username!' }]}
                >
                    <Input />
                </Form.Item>

                <br/>
                <br/>

                <Form.Item wrapperCol={{ offset: 10, span: 16 }}>
                    <Button type="primary" htmlType="submit">
                        登陆
                    </Button>
                </Form.Item>
            </Form>
        </div>
    )
}
export default LoginInput;